package com.rtf.framework.monitor.export;

import com.rtf.framework.common.support.redis.client.lb.AppRedisCircuitBreaker;
import com.rtf.framework.monitor.AppMonitorExporter;
import com.rtf.framework.monitor.config.AppMonitorProperties;
import com.google.common.collect.Lists;
import io.prometheus.client.Collector;
import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.GaugeMetricFamily;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/**
 * redis熔断监控
 * @Author : liupeng
 * @Date : 2020-01-20
 * @Modified By
 */
public class AppRedisExport extends Collector implements AppMonitorExporter {
    @Override
    public String getName() {
        return "redis";
    }

    @Override
    public List<MetricFamilySamples> collect() {
        List<MetricFamilySamples> mfs = Lists.newArrayList( ) ;
        Collection<AppRedisCircuitBreaker> appRedisCircuitBreakers = AppRedisCircuitBreaker.getInstances() ;
        if( appRedisCircuitBreakers==null || appRedisCircuitBreakers.size()<1 ){
            return mfs ;
        }

        // 标签属性
        List<String> labels = Arrays.asList("host" , "appName") ;

        GaugeMetricFamily redisCircuitBreakerGauge = new GaugeMetricFamily("redis_circuit_breaker_open",
                "redis是否熔断", labels ) ;

        for (AppRedisCircuitBreaker appRedisCircuitBreaker : appRedisCircuitBreakers) {

            List<String> labelValues = Arrays.asList( appRedisCircuitBreaker.getHost() , AppMonitorProperties.getAppName()  ) ;

            redisCircuitBreakerGauge.addMetric( labelValues , appRedisCircuitBreaker.isCircuitBreakerTripped() ? 1 : 0 ) ;
        }

        mfs.addAll( Lists.newArrayList( redisCircuitBreakerGauge ) ) ;

        return mfs ;
    }

    @Override
    public void export(CollectorRegistry collectorRegistry) {
        new AppRedisExport().register( collectorRegistry ) ;
    }
}
